package com.ty.service.impl;

import com.ty.config.Minio;
import com.ty.service.MinioService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    Minio minio;

    @Autowired
    MinioClient minioClient;

    @PostConstruct
    void init(){

        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minio.getBucketName()).build());
            if (!exists){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minio.getBucketName()).build());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public String update(MultipartFile file) {

        String oriFileName = file.getOriginalFilename();
        String extension = oriFileName.substring(oriFileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        String newfile =uuid+extension;

        String datetime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String filePath = datetime+"/"+newfile;

       try {
           minioClient.putObject(PutObjectArgs.builder()
                   .bucket(minio.getBucketName())
                   .object(filePath)
                   .stream(file.getInputStream(), file.getSize(), -1)
                   .contentType(file.getContentType())
                   .build());
       }catch (Exception e){
           throw new RuntimeException("文件上传不成功");
       }
        return minio.getUrl()+"/"+minio.getBucketName()+"/"+filePath;
    }

    @Override
    public ResponseEntity<InputStreamResource> download(String url) {

        url =url.split(minio.getUrl()+"/")[1];

        try{
           InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(minio.getBucketName())
                            .object(url)
                    .build());

            return  ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION,"attachment,filename:"+url)
                    .body(new InputStreamResource(inputStream));

        }catch (Exception e){
            throw new RuntimeException("文件下载失败");
        }
    }


}
